<?php

namespace App\HttpController\Admin;

use App\Model\MenusModel;
use App\Utility\MiniProgram;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;

class MenuController extends AuthController {

    public function index(){
        $info = MysqlPool::invoke(function (MysqlObject $db){
            $model  = new MenusModel($db);
            return $model->first();
        });
        return $this->writeJson(0,$info);
    }

    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $navs = [];

        foreach ($data['menu'] as $key=>$menu){
            if (empty($menu['title'])) {
                return $this->writeJson(1,null,'菜单名称不能为空');
            }
            $navs[$key]['name'] = $menu['title'];
            if(count($menu['child'])){
                $navs[$key]['sub_button'] = [];
                foreach ($menu['child'] as $k=>$m){
                    if (get_headers($m['value']) === false) {
                        return $this->writeJson(1,null,$m['title'].'链接：'.$m['value'].'不合法');
                    }
                    $navs[$key]['sub_button'][$k]['name'] = $m['title'];
                    $navs[$key]['sub_button'][$k]['type'] = 'view';
                    $navs[$key]['sub_button'][$k]['url'] = $m['value'];
                }
            }else{
                $data['menu'][$key]['child'] = [];
                if (get_headers($menu['value']) === false) {
                    return $this->writeJson(1,null,$menu['title'].'链接：'.$menu['value'].'不合法');
                }
                $navs[$key]['type'] = 'view';
                $navs[$key]['url'] = $menu['value'];
            }
        }

        try{
            MysqlPool::invoke(function (MysqlObject $db) use($data,$navs){
                $model = new MenusModel($db);
                $model->update(['id'=>1,'menu'=>$data['menu']]);
                $wechat = new MiniProgram();
                $wechat->createMenu(['button'=>$navs]);
                return $this->writeJson(0,$data,'编辑菜单信息成功');
            });
        }catch (\Throwable $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

}
